package com.atguigu.guli.service.vod.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.vod.properties.VodProperties;
import com.atguigu.guli.service.vod.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
    从前到后
        业务分析
    从后到前：
 */
@Service
@Slf4j
public class MediaServiceImpl implements MediaService {
    @Autowired
    VodProperties vodProperties;
    @Override
    public String upload(MultipartFile file, Integer encrypt) {
        try {
                //加密上传
                String title = file.getOriginalFilename();
                InputStream is = file.getInputStream();
                UploadStreamRequest request = new UploadStreamRequest(vodProperties.getAccessKeyId(), vodProperties.getAccessKeySecret()
                        , title, title, is);//通过流上传文件
                //上传后vod对视频自动进行转码加密审核的操作
                if(encrypt==1){
                    request.setWorkflowId(vodProperties.getWorkflowId());
                }
                UploadVideoImpl uploader = new UploadVideoImpl();
                UploadStreamResponse response = uploader.uploadStream(request);
                if (response.isSuccess()) {
                    return response.getVideoId();
                } else {
                    /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
                    System.out.print("VideoId=" +  response.getVideoId() +  "\n");
                    System.out.print("ErrorCode="  + response.getCode()  + "\n");
                    System.out.print("ErrorMessage=" +  response.getMessage() +  "\n");
                    throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
                }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }

    }
    //初始化客户端
    public DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = vodProperties.getRegionId();  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
    @Override
    public String getPlayUrl(String vid) {
        DefaultAcsClient client = initVodClient(vodProperties.getAccessKeyId(), vodProperties.getAccessKeySecret());
        GetPlayInfoResponse response;
        try {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(vid); // 根据视频的id获取视频的播放地址
            response = client.getAcsResponse(request);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            //播放地址
            GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
            String playURL = playInfo.getPlayURL();
            return playURL;
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));//出现异常的真正的原因
           throw new GuliException(ResultCodeEnum.FETCH_PLAYURL_ERROR); //通过全局异常处理器处理响应给前端提示
        }

    }

    @Override
    public String getPlayAuth(String vid) {
        DefaultAcsClient client = initVodClient(vodProperties.getAccessKeyId(), vodProperties.getAccessKeySecret());
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        try {
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(vid);
            request.setAuthInfoTimeout(3000L); //播放凭证的过期时间 默认100秒，最大可以设置为3000秒
            response = client.getAcsResponse(request);
            return response.getPlayAuth();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR);
        }

    }
}
